﻿using DataBase;
using DataBase.Utils;
using GreenXi.Help.Curve;
using GreenXi.Model;
using GreenXi.Pages.Power;
using GreenXi.Pages.Power;
using Prism.Commands;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Windows.Forms;
using Util.Model;
using Util;
using ZedGraph;
using static GreenXi.Help.Curve.SmoothChart;

namespace GreenXi.ViewModel
{
    public class MonitoringViewModel : MonitoringModel
    {
        /// <summary>
        /// 初始化
        /// </summary>
        private static string PressId = "1";




        private static int id = 0;

        public static Double X1 = 0;
        public static Double X2 = 0;
        public static Double Y1 = 0;
        public static Double Y2 = 0;

        public static string Xstr = "";
        public static string Ystr = "";
        //记录当前点xy坐标
        private static double oldx = 0;
        private static double oldy = 0;
        //点击的第几个框
        private static int Num = 0;

        //点击的第几个框
        private static int DecisionId = 0;

        //点击的是节点还是内部 
        private static int node = 0;

        //鼠标拖拽状态
        private bool isDragging = false;
        //保留小数位数
        private int DecimalPlaces = 2;

        //选中的线是哪条
        private static short SelectNum = 1;
        //是否画曲线
        private static bool IsCurve = false;
        //曲线
        private LineItem Curves = null;
        //点
        PointPairList listMainChart = new PointPairList();

        PointPairList listMainChart2 = new PointPairList();

        private List<Decision> Decisionlist;


        public Action CloseAction { get; set; }
        Monitoring context;
        public void Init()
        {

            ObservableCollection<Decision> TableLists = new ObservableCollection<Decision>();
            Decisionlist = MyDbContext.Instance.GetDecisionByFuncName(CylinderNo, PressId);
            foreach (var item in Decisionlist)
            {
                TableLists.Add(item);
            }
            TableList = TableLists;
            ImagePaths = new ObservableCollection<DecisionType>();
            var ImagePathsList = MyDbContext.Instance.GetDecisionType();
            foreach (var item in ImagePathsList)
            {
                ImagePaths.Add(item);
            }

            SwitchPressButton();
            var setting = MyDbContext.Instance.GetValueByKey("DecimalPlaces");
            DecimalPlaces = Convert.ToInt32(setting.Value);
            #region ZedGraph 初始化

            zedGraphInit(context.zedGraphControl, PressId);

            if (GlobalVariables.CompressorsNumber == 2)
            {
                IsVisibility = "Visible";
            }

            #endregion
        }
        public MonitoringViewModel(Monitoring _context)
        {
            context = _context;
            Init();//初始化

            ImageClickCommand = new DelegateCommand<object>((p) => { OnImageClick(p); });
            UpdateColumn = new DelegateCommand<object>((p) => { UpdateColumn_Click(p); });
            AlertDecision = new DelegateCommand<object>((p) => { AlertDecision_Click(p); }); //弹出判断框
            AddColumn = new DelegateCommand(() => { AddColumn_Click(); });//新增栏目
            SwitchPress = new DelegateCommand<object>((p) => { SwitchPress_Click(p); }); //切换压机
            DelColumn = new DelegateCommand<object>((p) => { DelColumn_Click(p); });//删除栏目
            Draw = new DelegateCommand<object>((p) => { Draw_Click(p); });

            OpenCuve = new DelegateCommand(() => { ViewCurvesByFile_Click(); });//通过文件查看曲线

            SelectFilter = new DelegateCommand<object>((p) => { SelectFilter_Click(p); }); //通过产品筛选判断框

            context.zedGraphControl.MouseDownEvent += ZedMouseEventHandler;
            //context.zedGraphControl.MouseMoveEvent += zedGraphControl1_MouseMoveEvent;
            context.zedGraphControl.MouseUpEvent += zedGraphControl1_MouseUpEvent;
        }
        private void AddColumn_Click()
        {
            var decisiontype = MyDbContext.Instance.GetDecisionType().FirstOrDefault();
            Decision decision = new Decision
            {
                Type = decisiontype.Name,
                X1 = 150,
                X2 = 200,
                Y1 = 0,
                Y2 = 80,
                PressId = PressId,
                ParentId = CylinderNo,
                Image = decisiontype.Image
            };
            if (decisiontype != null)
            {
                TableList.Add(decision);
            }
            MyDbContext.Instance.DecisionAdd(decision);
        }
        private void Draw_Click(object param)
        {
            Init();
            DecisionId = (int)param;
        }

        private void SelectFilter_Click(object param)
        {
            //
            zedGraphInit(context.zedGraphControl, PressId);
            Decisionlist = MyDbContext.Instance.GetDecisionByFuncName(CylinderNo, PressId);
            TableList = new(Decisionlist);
        }



        private void AlertDecision_Click(object param)
        {
            var paramss = param as Decision;
            Pages.index.Decision decision = new Pages.index.Decision();
            id = paramss.ID;
            //加个判断
            if (decision.IsLoaded == false)
            {
                decision.Closed += Decision_Closed;
                decision.Show();
            }
        }
        private void Decision_Closed(object sender, EventArgs e)
        {
            Init();
        }
        //更新
        private void UpdateColumn_Click(object param)
        {
            var paramss = param as Decision;
            MyDbContext.Instance.DecisionUpdate(paramss);
            Init();
        }
        //压机切换
        private void SwitchPress_Click(object param)
        {
            PressId = param.ToString();
            Init();
        }

        private void DelColumn_Click(object param)//删除栏目
        {
            var paramss = param as Decision;
            MyDbContext.Instance.DecisionDel(paramss);
            Init();
        }
        private void OnImageClick(object parameter)
        {
            Curves = null;
            Xstr = "";
            Ystr = "";


            using MyDbContext myDbContext = new();
            var parameters = parameter as DecisionType;
            DataBase.Decision decision = myDbContext.Decisions.FirstOrDefault(x => x.ID == Convert.ToInt32(id));
            decision.Type = parameters.Name;
            decision.Image = parameters.Image;
            if (id != 0)
            {
                decision.ID = Convert.ToInt32(id);
                decision.PressId = PressId;
                MyDbContext.Instance.DecisionUpdate(decision);
            }
            else
            {
                decision.X1 = 10;
                decision.X2 = 20;
                decision.Y1 = 20;
                decision.Y2 = 50;
                MyDbContext.Instance.DecisionAdd(decision);

            }
            if (decision.Type == "曲线")
            {
                IsCurve = true;
                Num = 1;
            }

            CloseAction();//关闭弹窗

        }
        public void zedGraphInit(ZedGraphControl zedGraphControl, string PressId)
        {
         
        }




        //鼠标移动
        private bool zedGraphControl1_MouseMoveEvent(ZedGraphControl sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (isDragging)
            {
                double x1, y1, movex, movey;

                // 将屏幕坐标转换为图像坐标
                sender.GraphPane.ReverseTransform(new PointF(e.X, e.Y), out x1, out y1);
                x1 = Math.Round(x1, DecimalPlaces);
                y1 = Math.Round(y1, DecimalPlaces);
                movex = x1 - oldx; movey = y1 - oldy;
                oldx = x1; oldy = y1;

                if (movex != 0 || movey != 0)
                {

                    ZedGraph.GraphPane myPane = context.zedGraphControl.GraphPane;
                    if (node == 0 && myPane != null)
                    {
                        for (int i = 0; i <= myPane.CurveList.Count; i++)
                        {

                            if (i < 4 * Num && i >= 4 * (Num - 1))
                            {

                                myPane.CurveList[i].Points[0].X = myPane.CurveList[i].Points[0].X + movex;
                                myPane.CurveList[i].Points[0].Y = myPane.CurveList[i].Points[0].Y + movey;
                                myPane.CurveList[i].Points[1].X = myPane.CurveList[i].Points[1].X + movex;
                                myPane.CurveList[i].Points[1].Y = myPane.CurveList[i].Points[1].Y + movey;
                                if (i == 4 * (Num - 1))
                                {
                                    X1 = Math.Round(X1 + movex, DecimalPlaces); Y1 = Math.Round(Y1 + movey, DecimalPlaces); X2 = Math.Round(X2 + movex, DecimalPlaces); Y2 = Math.Round(Y2 + movey, DecimalPlaces);
                                }
                            }
                        }
                    }
                    else
                    {
                        double xx1 = 0, yy1 = 0, xx2 = 0, yy2 = 0;
                        if (node == 1)
                        {
                            xx1 = x1;
                            yy1 = y1;
                        }
                        if (node == 2)
                        {
                            xx2 = x1;
                            yy1 = y1;
                        }
                        if (node == 3)
                        {
                            xx2 = x1;
                            yy2 = y1;
                        }
                        if (node == 3)
                        {
                            xx2 = x1;
                            yy2 = y1;
                        }
                        if (node == 4)
                        {
                            xx1 = x1;
                            yy2 = y1;
                        }
                        X1 = xx1 == 0 ? X1 : xx1;
                        X2 = xx2 == 0 ? X2 : xx2;
                        Y1 = yy1 == 0 ? Y1 : yy1;
                        Y2 = yy2 == 0 ? Y2 : yy2;
                        int count = 0;
                        for (int i = 0; i <= myPane.CurveList.Count; i++)
                        {
                            if (i < 4 * Num && i >= 4 * (Num - 1))
                            {
                                count++;
                                if (count == 1)
                                {
                                    myPane.CurveList[i].Points[0].X = xx1 == 0 ? myPane.CurveList[i].Points[0].X : xx1;
                                    myPane.CurveList[i].Points[0].Y = yy1 == 0 ? myPane.CurveList[i].Points[0].Y : yy1;
                                    myPane.CurveList[i].Points[1].X = xx2 == 0 ? myPane.CurveList[i].Points[1].X : xx2;
                                    myPane.CurveList[i].Points[1].Y = yy1 == 0 ? myPane.CurveList[i].Points[1].Y : yy1;
                                }
                                if (count == 2)
                                {
                                    myPane.CurveList[i].Points[0].X = xx2 == 0 ? myPane.CurveList[i].Points[0].X : xx2;
                                    myPane.CurveList[i].Points[0].Y = yy1 == 0 ? myPane.CurveList[i].Points[0].Y : yy1;
                                    myPane.CurveList[i].Points[1].X = xx2 == 0 ? myPane.CurveList[i].Points[1].X : xx2;
                                    myPane.CurveList[i].Points[1].Y = yy2 == 0 ? myPane.CurveList[i].Points[1].Y : yy2;
                                }
                                if (count == 3)
                                {
                                    myPane.CurveList[i].Points[0].X = xx2 == 0 ? myPane.CurveList[i].Points[0].X : xx2;
                                    myPane.CurveList[i].Points[0].Y = yy2 == 0 ? myPane.CurveList[i].Points[0].Y : yy2;
                                    myPane.CurveList[i].Points[1].X = xx1 == 0 ? myPane.CurveList[i].Points[1].X : xx1;
                                    myPane.CurveList[i].Points[1].Y = yy2 == 0 ? myPane.CurveList[i].Points[1].Y : yy2;
                                }
                                if (count == 4)
                                {
                                    myPane.CurveList[i].Points[0].X = xx1 == 0 ? myPane.CurveList[i].Points[0].X : xx1;
                                    myPane.CurveList[i].Points[0].Y = yy2 == 0 ? myPane.CurveList[i].Points[0].Y : yy2;
                                    myPane.CurveList[i].Points[1].X = xx1 == 0 ? myPane.CurveList[i].Points[1].X : xx1;
                                    myPane.CurveList[i].Points[1].Y = yy1 == 0 ? myPane.CurveList[i].Points[1].Y : yy1;
                                }

                            }
                        }
                    }



                    context.zedGraphControl.AxisChange();
                    context.zedGraphControl.Refresh();
                }
            }
            return false;
        }
        //鼠标点击
        public bool ZedMouseEventHandler(ZedGraphControl sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                // 将屏幕坐标转换为图像坐标
                sender.GraphPane.ReverseTransform(new PointF(e.X, e.Y), out oldx, out oldy);
                oldx = Math.Round(oldx, 2);
                oldy = Math.Round(oldy, 2);
                //判断是否是在画曲线
                if (IsCurve)
                {
                    if (string.IsNullOrEmpty(Xstr))
                    {
                        //将点加入曲线中
                        listMainChart.Add(oldx, oldy);
                        Curves = sender.GraphPane.AddCurve("", listMainChart, System.Drawing.Color.Red);

                        Curves.Symbol.IsVisible = true;
                        Curves.Line.IsAntiAlias = false;
                        Xstr = oldx.ToString();
                        Ystr = oldy.ToString();
                    }
                    else
                    {
                        listMainChart.Add(oldx, oldy);
                        Xstr += "," + oldx;
                        Ystr += "," + oldy;
                    }
                    //更新数据库
                    SaveDecision(Xstr, Ystr);
                    #region
                    zedGraphInit(context.zedGraphControl, PressId);
                    #endregion

                    return false;
                }
                // 检查鼠标位置是否在图形对象内
                Num = isinside(sender.GraphPane.CurveList, oldx, oldy);
                if (Num > 0)//点击在判断框内
                {
                    isDragging = true;
                }
            }
            else if (e.Button == MouseButtons.Right)
            {
                //右键
                IsCurve = false;
            }
            return false;

        }
        //判断一个点是否在矩形内部
        public static int isinside(CurveList curveitems, double x, double y)
        {

            //4个一循环
            int count = 0;
            for (int i = 0; i < curveitems.Count; i++)
            {
                var points = curveitems[i].Points;
                if (points.Count > 2)
                {
                    #region 循环判断是否点击点
                    for (int j = 0; j < points.Count; j++)
                    {
                        X1 = 0; X2 = 0; Y1 = 0; Y2 = 0;
                        X1 = points[j].X; Y1 = points[j].Y;
                        var DifX = Math.Abs(x - X1);
                        var DifY = Math.Abs(x - Y1);
                        if (DifX + DifY < 5)//判定是点击了
                        {
                            return (i + 1) / 4 + (i + 1) % 4;
                        }
                    }

                    #endregion
                }
                else
                {
                    count++;
                    if (count == 4)
                    {
                        count = 0;
                        points = curveitems[i - 3].Points;
                        X1 = 0; X2 = 0; Y1 = 0; Y2 = 0;


                        X1 = points[0].X;
                        Y1 = points[0].Y;
                        X2 = points[1].X;
                        Y2 = curveitems[i - 2].Points[1].Y;

                        node = 0;
                        if (Math.Abs(x - X1) < 5)
                        {
                            if (Math.Abs(y - Y1) < 5)
                            {
                                node = 1;
                            }
                            if (Math.Abs(y - Y2) < 5)
                            {
                                node = 4;
                            }
                        }
                        if (Math.Abs(x - X2) < 5)
                        {
                            if (Math.Abs(y - Y1) < 5)
                            {
                                node = 2;
                            }
                            if (Math.Abs(y - Y2) < 5)
                            {
                                node = 3;
                            }
                        }

                        if ((x > X1 && x < X2 && y > Y1 && y < Y2) || node != 0)
                        {
                            return (i + 1) / 4;
                        }
                    }
                }

            }
            return 0;
        }
        //鼠标松开
        private bool zedGraphControl1_MouseUpEvent(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            //using MyDbContext myDbContext = new();
            //isDragging = false;
            ////存储到数据库
            //if (Num != 0)
            //{
            //    Decisionlist = myDbContext.GetDecision(PressId);
            //    var paramss = myDbContext.Decisions.FirstOrDefault(x => x.ID == DecisionId);
            //    paramss.X1 = X1;
            //    paramss.Y1 = Y1;
            //    paramss.X2 = X2;
            //    paramss.Y2 = Y2;

            //    myDbContext.DecisionUpdate(paramss);
            //    ObservableCollection<Decision> TableLists = new ObservableCollection<Decision>();
            //    Decisionlist = myDbContext.GetDecision(PressId);
            //    foreach (var item in Decisionlist)
            //    {
            //        TableLists.Add(item);
            //    }
            //    TableList = TableLists;
            //    ImagePaths = new ObservableCollection<DecisionType>();
            //    var ImagePathsList = myDbContext.GetDecisionType();
            //    foreach (var item in ImagePathsList)
            //    {
            //        ImagePaths.Add(item);
            //    }
            //}

            return isDragging;
        }
        /// <summary>
        /// 把点保存在数据库
        /// </summary>
        public void SaveDecision(string Xstr, string Ystr)
        {
            var decision = MyDbContext.Instance.Decisions.Find(Convert.ToInt32(id));
            if (decision != null)
            {
                decision.X1str = Xstr;
                decision.Y1str = Ystr;
                MyDbContext.Instance.DecisionUpdate(decision);
            }

        }

        /// <summary>
        /// 控制按钮显隐
        /// </summary>
        /// <param name="pressNum"></param>
        public void SwitchPressButton()
        {
            Press1 = true;
            Press2 = true;
            switch (PressId)
            {
                case "1":
                    Press1 = false;
                    break;
                case "2":
                    Press2 = false;
                    break;
                default: break;
            }
        }

        /// <summary>
        /// 根据文件查看曲线
        /// </summary>
        /// <param name="param"></param>
        private void ViewCurvesByFile_Click()
        {
            //获取要查看的文件
            // 创建一个打开文件对话框实例
            Microsoft.Win32.OpenFileDialog openFileDialog = new();

            // 设置对话框的标题和筛选条件（可选）
            openFileDialog.Title = "选择文件";
            openFileDialog.Filter = "CSV文件 (*.CSV)|*.CSV";

            // 显示对话框并获取用户的操作结果
            bool? result = openFileDialog.ShowDialog();

            if (result == true)
            {
                // 获取所选文件的完整路径
                string selectedFilePath = openFileDialog.FileName;
                CSVUtil util = new();
                List<CSVData> dataList;
                List<Util.Model.Border> borderList;

                util.ReadFromCsv(selectedFilePath, out dataList, out borderList);



                foreach (var item in dataList)
                {
                    listMainChart2.Add(item.CurrentPosition, item.CurrentPosition);
                }


                //.AddCurve("压力-位移实时曲线", List, Color.Green, SymbolType.Diamond)
                var cure = context.zedGraphControl.GraphPane.AddCurve("", listMainChart2, System.Drawing.Color.Green);
                cure.Symbol.IsVisible = false;
                cure.Line.IsAntiAlias = false;
                context.zedGraphControl.AxisChange();
                context.zedGraphControl.Refresh();


            }

        }
    }
}
